<template>
  <teleport to="#commManageRight"
    ><div class="friManageFris-menu" v-show="isRender">
      <transition name="fmenuCollapse"
        ><div class="friManageFris-menu__content" v-show="show">
          <SvgIcon icon-class="close" popper-class="menuCloseIcon" @click="ids.clear()" />
          <span style="font-size: 14px">已选择 {{ ids.size }} 人</span>
          <div class="menuContent-right">
            <i class="flex" @click="openDialog(1)"
              ><SvgIcon icon-class="delete" popper-class="menuIcon" title="删除好友"
            /></i>
            <i class="flex" v-show="showMoveIcon" @click="openDialog(2)"
              ><SvgIcon icon-class="move" popper-class="menuIcon" title="移出分组"
            /></i>
            <i class="flex" v-show="ids.size === 1" @click="openDialog(3)"
              ><SvgIcon icon-class="permission" popper-class="menuIcon" title="修改权限"
            /></i>
            <i class="flex" v-show="showGroupIcon" @click="openDialog(4)"
              ><SvgIcon icon-class="group" popper-class="menuIcon" title="设置分组"
            /></i>
          </div></div
      ></transition></div
  ></teleport>
  <confirm-dialog
    to=".chat-box"
    v-model="showDialog"
    width="35%"
    :title="titleText"
    :isLoading="isLoading"
    @confirm="confirm(executeType)"
  >
    <p v-if="executeType === 1">确定删除该{{ ids.size }}位好友？</p>
    <p v-else-if="executeType === 2">确定将{{ ids.size }}位好友从该分组移出？</p>
    <div v-else-if="executeType === 3" class="friManageFris-dialog__main">
      <moments-permission
        :disabled="isLoading"
        v-model="theInfoPermission"
      ></moments-permission>
    </div>
    <div class="friManageFris-dialog__main" v-else-if="executeType === 4">
      <el-input
        v-model.trim="currentGroup"
        ref="groupRef"
        :disabled="isLoading"
        maxlength="16"
        placeholder="设置分组"
        @keypress.enter.prevent="confirm(executeType)"
        style="margin-bottom: 15px"
      /><group-tags :disabled="isLoading" @change="groupChange"></group-tags>
    </div>
  </confirm-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, nextTick } from "vue";
import { useUserPinia } from "@/pinia/user";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";
import confirmDialog from "@/components/confirmDialog.vue";
import { useFriendPinia } from "@/pinia/friend";
import groupTags from "@/components/groupTags.vue";

const props = withDefaults(
  defineProps<{
    modelValue: boolean;
    ids: Set<string>;
    showMoveIcon?: boolean;
    showGroupIcon?: boolean;
    group: string;
    infoPermission: Permission;
  }>(),
  {
    showMoveIcon: true,
    showGroupIcon: true,
  }
);

const friendStore = useFriendPinia();
const { user } = storeToRefs(useUserPinia());

/**
 * 对对方的朋友圈权限
 */
const theInfoPermission = ref<Permission>({
  disabledOtherLook: props.infoPermission.disabledOtherLook,
  disabledSelfLook: props.infoPermission.disabledSelfLook,
});

watch(
  () => props.infoPermission,
  (permission) => {
    theInfoPermission.value.disabledOtherLook = permission.disabledOtherLook;
    theInfoPermission.value.disabledSelfLook = permission.disabledSelfLook;
  },
  { deep: true }
);

/**
 * 是否开始显示此组件
 */
const isRender = ref<boolean>(false);
/**
 * 是否显示内容
 */
const show = ref<boolean>(false);

watch(
  () => props.modelValue,
  (newValue: boolean) => {
    if (newValue) {
      isRender.value = newValue;
      nextTick(() => (show.value = newValue));
    } else {
      show.value = newValue;
      setTimeout(() => (isRender.value = newValue), 250);
    }
  }
);

/**
 * 是否显示操作确认对话框
 */
const showDialog = ref<boolean>(false);
/**
 * 当前操作执行的类型(1 代表删除操作，2代表移出分组，3代表修改权限，4代表设置分组)
 */
const executeType = ref<1 | 2 | 3 | 4>(1);
/**
 * 执行哪类操作的文本提示
 */
const titleText = ref<string>("");
/**
 * 是否正在执行某项操作
 */
const isLoading = ref<boolean>(false);
/**
 * 给设置分组输入框一个ref属性
 */
const groupRef = ref<any>();
/**
 * 当前用户修改后的分组名
 */
const currentGroup = ref<string>("");

// 当分组发生改变时
const groupChange = (group: string) => (currentGroup.value = group);

// 准备打开对话框
const openDialog = (type: 1 | 2 | 3 | 4) => {
  executeType.value = type;
  switch (type) {
    case 1:
      titleText.value = "删除好友";
      break;
    case 2:
      titleText.value = "移出分组";
      break;
    case 3:
      titleText.value = "修改权限";
      break;
    case 4:
      titleText.value = "设置分组";
      currentGroup.value = props.group;
      setTimeout(() => groupRef.value.focus(), 200);
      break;
  }
  showDialog.value = true;
};

// 确认执行
const confirm = (type: 1 | 2 | 3 | 4) => {
  switch (type) {
    case 1:
      isLoading.value = true;
      friendStore
        .deleteFriend({
          selfId: user.value.userId,
          otherIds: [...props.ids.values()],
        })
        .then((code) => {
          isLoading.value = false;
          if (code === 1) {
            showDialog.value = false;
            props.ids.clear();
            ElMessage({
              type: "success",
              message: "删除成功",
              duration: 1500,
            });
          } else
            ElMessage({
              type: "error",
              message: "删除失败",
              duration: 1500,
            });
        })
        .catch(() => {
          isLoading.value = false;
          ElMessage({
            type: "error",
            message: "删除失败",
            duration: 1500,
          });
        });
      break;
    case 2:
      isLoading.value = true;
      friendStore
        .moveGroup({
          selfId: user.value.userId,
          otherIds: [...props.ids.values()],
          group: props.group,
        })
        .then((code: number) => {
          isLoading.value = false;
          if (code === 1) {
            showDialog.value = false;
            props.ids.clear();
            ElMessage({
              type: "success",
              message: "移出成功",
              duration: 1500,
            });
          } else
            ElMessage({
              type: "error",
              message: "移出失败",
              duration: 1500,
            });
        })
        .catch(() => {
          isLoading.value = false;
          ElMessage({
            type: "error",
            message: "移出失败",
            duration: 1500,
          });
        });
      break;
    case 3:
      if (
        !(
          props.infoPermission.disabledOtherLook ===
            theInfoPermission.value.disabledOtherLook &&
          props.infoPermission.disabledSelfLook ===
            theInfoPermission.value.disabledSelfLook
        )
      ) {
        const permission: {
          type: "disabledOtherLook" | "disabledSelfLook" | "other";
          count: 1 | -1;
          changeType: 0 | 1 | 2 | 3;
        } = {
          type: "disabledSelfLook",
          count: -1,
          changeType: 0,
        };
        // 如果请求了通讯管理数据的话
        if (
          props.infoPermission.disabledOtherLook ===
            theInfoPermission.value.disabledOtherLook &&
          props.infoPermission.disabledSelfLook !==
            theInfoPermission.value.disabledSelfLook
        ) {
          // 代表只需要不看对方的总人数+1
          if (theInfoPermission.value.disabledSelfLook) permission.count = 1;
        } else if (
          props.infoPermission.disabledOtherLook !==
            theInfoPermission.value.disabledOtherLook &&
          props.infoPermission.disabledSelfLook ===
            theInfoPermission.value.disabledSelfLook
        ) {
          permission.type = "disabledOtherLook";
          // 代表只需要不让对方看的总人数+1
          if (theInfoPermission.value.disabledOtherLook) permission.count = 1;
        } else {
          permission.type = "other";
          if (
            theInfoPermission.value.disabledOtherLook &&
            theInfoPermission.value.disabledSelfLook
          )
            // 两方都需要+1
            permission.changeType = 1;
          else if (
            theInfoPermission.value.disabledOtherLook &&
            !theInfoPermission.value.disabledSelfLook
          )
            // 不让对方看的人数+1，自己不看的人数-1
            permission.changeType = 2;
          else if (
            !theInfoPermission.value.disabledOtherLook &&
            theInfoPermission.value.disabledSelfLook
          )
            // 不让对方看的人数-1，自己不看的人数+1
            permission.changeType = 3;
        }
        isLoading.value = true;
        friendStore
          .updateMomPermission(
            {
              otherId: [...props.ids.values()][0],
              disabledOtherLook: theInfoPermission.value.disabledOtherLook,
              disabledSelfLook: theInfoPermission.value.disabledSelfLook,
            },
            props.group,
            permission
          )
          .then((code: number) => {
            isLoading.value = false;
            if (code === 1) {
              showDialog.value = false;
              props.ids.clear();
              ElMessage({
                type: "success",
                message: "修改成功",
                duration: 1500,
              });
            } else if (code === -2)
              ElMessage({
                type: "error",
                message: "修改失败，对方和自己不是好友关系",
                duration: 1500,
              });
            else
              ElMessage({
                type: "error",
                message: "修改失败",
                duration: 1500,
              });
          })
          .catch(() => {
            isLoading.value = false;
            ElMessage({
              type: "error",
              message: "修改失败",
              duration: 1500,
            });
          });
      } else {
        showDialog.value = false;
        props.ids.clear();
      }
      break;
    case 4:
      if (currentGroup.value === props.group) {
        showDialog.value = false;
        props.ids.clear();
      } else {
        isLoading.value = true;
        friendStore
          .updateGroup(
            {
              selfId: user.value.userId,
              group: currentGroup.value,
              otherIds: [...props.ids.values()],
            },
            props.group
          )
          .then((code) => {
            isLoading.value = false;
            if (code === 1) {
              showDialog.value = false;
              props.ids.clear();
              ElMessage({
                type: "success",
                message: "修改成功",
                duration: 1500,
              });
            } else {
              ElMessage({
                type: "error",
                message: "修改失败",
                duration: 1500,
              });
              groupRef.value.focus();
            }
          })
          .catch(() => {
            isLoading.value = false;
            ElMessage({
              type: "error",
              message: "修改失败",
              duration: 1500,
            });
            groupRef.value.focus();
          });
      }
      break;
  }
};
</script>

<style lang="scss" scoped>
.fmenuCollapse {
  &-enter-active,
  &-leave-active {
    transition: transform 0.25s;
  }

  &-enter-from,
  &-leave-to {
    transform: translateY(70px);
  }
}

.friManageFris {
  &-menu {
    height: 70px;
    overflow: hidden;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;

    &__content {
      background-color: rgb(243, 249, 254);
      height: 100%;
      line-height: 70px;
      padding-left: 20px;
      position: relative;

      .menuCloseIcon {
        font-size: 18px;
        margin-right: 20px;
        vertical-align: middle;
        cursor: pointer;
        transition: color 0.15s;

        &:hover {
          color: #79bbff;
        }
      }

      .menuContent-right {
        position: absolute;
        top: 0;
        right: 5%;
        bottom: 0;
        display: flex;
        align-items: center;

        i {
          @include setWidHei(40px, 40px);
          background-color: #fff;
          border-radius: 50%;
          cursor: pointer;
          margin-right: 18px;

          &:hover {
            .menuIcon {
              opacity: 1;
            }
          }

          .menuIcon {
            font-size: 18px;
            color: #333;
            opacity: 0.7;
          }
        }
      }
    }
  }

  &-dialog {
    &__main {
      width: 70%;
      display: inline-block;
      text-align: left;
    }
  }
}
</style>
